package com.tbvtc.agriculturalcreditchainserver2025.utils;

import org.springframework.web.multipart.MultipartFile;
import java.io.*;

public class CustomMultipartFile implements MultipartFile {
    private final byte[] fileBytes;
    private final String fieldName;
    private final String originalFilename;
    private final String contentType;

    /**
     * 构造函数
     * @param fileBytes 文件的字节数组
     * @param fieldName 表单字段名（需与接口 @RequestParam 名称一致）
     * @param originalFilename 原始文件名（如 "image.jpg"）
     * @param contentType 文件类型（如 "image/jpeg"）
     */
    public CustomMultipartFile(byte[] fileBytes, String fieldName, String originalFilename, String contentType) {
        this.fileBytes = fileBytes;
        this.fieldName = fieldName;
        this.originalFilename = originalFilename;
        this.contentType = contentType;
    }

    // 实现 MultipartFile 接口的所有方法

    @Override
    public String getName() {
        return this.fieldName;
    }

    @Override
    public String getOriginalFilename() {
        return this.originalFilename;
    }

    @Override
    public String getContentType() {
        return this.contentType;
    }

    @Override
    public boolean isEmpty() {
        return fileBytes == null || fileBytes.length == 0;
    }

    @Override
    public long getSize() {
        return fileBytes.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return fileBytes;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(fileBytes);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        try (FileOutputStream fos = new FileOutputStream(dest)) {
            fos.write(fileBytes);
        }
    }
}